from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from freight.models import maininfo
import json
from EMC.public import *
import csv
import time
import uuid
# Create your views here.

def freight_maininfo(request):
    if request.user.is_authenticated(): 
        t = get_template('../templates/freight_maininfo.tpl')
        html = t.render(Context({'current_date': 'ADMIN'}))
        return HttpResponse(html)
    else:
        return HttpResponseRedirect('account/login')
def freight_maininfo_get(request):
    try:
        result = []
        result1 = {}
        table = maininfo.objects.query_freight()
        for row in table:
            result.append({"FREIGHT_ID":row["FREIGHT_ID"],"FORWARDER":row["FORWARDER"], "TRACKING_NR":row["TRACKING_NR"], "WEIGHT":row["WEIGHT"], "PALLET":row["PALLET"],"BOXES":row["BOXES"],"AMOUNT":row["AMOUNT"],"RECEIVING_DATE":row["RECEIVING_DATE"],})
        result1 = {"total":len(result),"rows":result}
    except Exception as e:
        print e[0]
    return HttpResponse(json.dumps(result1))

def freight_maininfo_post(request):
    counts = {'inserted':0,'updated':0,'deleted':0}
    error = ""
    try:
        if 'inserted' in request.POST and request.POST['inserted']:
            insertdata = request.POST['inserted']
            if len(insertdata) > 0:
                for row in json.loads(insertdata):
                    insertrow = maininfo.objects.create(TRACKING_NR=row["TRACKING_NR"],WEIGHT=row["WEIGHT"],PALLET=row["PALLET"],BOXES=row["BOXES"],AMOUNT=row["AMOUNT"])
                    counts['inserted'] +=1

        if 'updated' in request.POST and request.POST['updated']:
            updatedata = request.POST['updated']
            if len(updatedata) > 0:
                for row in json.loads(updatedata):
                    if maininfo.objects.filter(FREIGHT_ID=row["FREIGHT_ID"]).update(TRACKING_NR=row["TRACKING_NR"],WEIGHT=row["WEIGHT"],PALLET=row["PALLET"],BOXES=row["BOXES"],AMOUNT=row["AMOUNT"])>0:
                        counts['updated'] +=1
        if 'deleted' in request.POST and request.POST['deleted']:
            deletedata = request.POST['deleted']
            if len(deletedata) > 0:
                for row in json.loads(deletedata):
                    maininfo.objects.filter(FREIGHT_ID=row["FREIGHT_ID"]).delete()
                    counts['deleted'] +=1
    except Exception as e:
        error = e[0]
        print error
    message = CMessage("Freight","Result(Inserted: %d, updated: %d, deleted: %d)" % (counts['inserted'],counts['updated'],counts['deleted']),error)
    return HttpResponse( message.ToJson())

def freight_maininfo_report(request):
    client_ip = request.META.get("REMOTE_ADDR", None)
    report_file = str(uuid.uuid1()) + str(uuid.uuid5(uuid.NAMESPACE_DNS,client_ip))+'.csv'
    report_writer = csv.writer(file('D:/temp/'+report_file, 'wb'))
    report_writer.writerow(['FREIGHT_ID','FORWARDER','TRACKING#','WEIGHT','PALLET','BOXES','AMOUNT','RECV_DATE'])
    table = maininfo.objects.query_freight()
    for row in table:
        report_writer.writerow([row['FREIGHT_ID'],row['FORWARDER'], row['TRACKING_NR'], row['WEIGHT'],row['PALLET'],row['BOXES'],row['AMOUNT'],row['RECEIVING_DATE']])
    return HttpResponse( report_file)